"""
热点数据获取服务
负责从各个平台获取热点数据
"""

from typing import Dict, Any, Optional
import aiohttp
from datetime import datetime
from app.core.logging import get_logger

from app.core.config import settings
from app.core.hot.platforms import platform_config
from app.models.hot import HotItem, HotResponse

logger = get_logger(__name__)


class HotDataService:
    """热点数据服务"""
    
    def __init__(self):
        self.session = None
        self.timeout = aiohttp.ClientTimeout(total=30)
    
    async def __aenter__(self):
        """异步上下文管理器进入"""
        connector = aiohttp.TCPConnector(limit=100, limit_per_host=10)
        self.session = aiohttp.ClientSession(
            connector=connector,
            timeout=self.timeout,
            headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        )
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """异步上下文管理器退出"""
        if self.session:
            await self.session.close()
    
    async def fetch_platform_data(self, platform: str) -> Optional[HotResponse]:
        """获取单个平台数据"""
        try:
            config = platform_config.get_platform(platform)
            if not config or not config.get("available", True):
                return None
            
            logger.info(f"开始获取 {platform} 数据")
            
            # 根据平台类型选择获取方式
            if platform == "zhihu":
                data = await self._fetch_zhihu()
            elif platform == "bilibili":
                data = await self._fetch_bilibili()
            elif platform == "weibo":
                data = await self._fetch_weibo()
            elif platform == "github":
                data = await self._fetch_github()
            elif platform == "36kr":
                data = await self._fetch_36kr()
            elif platform == "v2ex":
                data = await self._fetch_v2ex()
            else:
                data = await self._fetch_generic(platform, config)
            
            return data
            
        except Exception as e:
            logger.error(f"获取 {platform} 数据失败: {str(e)}")
            return None
    
    async def _fetch_zhihu(self) -> Optional[HotResponse]:
        """获取知乎热榜"""
        try:
            url = "https://api.zhihu.com/topstory/hot-lists/total"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://www.zhihu.com/hot',
                'Cookie': settings.ZHIHU_COOKIE or ''
            }
            
            async with self.session.get(url, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    for idx, item in enumerate(data.get('data', [])):
                        target = item.get('target', {})
                        url = f"https://www.zhihu.com/question/{target.get('id', '')}"
                        items.append(HotItem(
                            id=str(item.get('id', idx)),
                            title=target.get('title', ''),
                            url=url,
                            mobile_url=url,  # 使用相同的URL作为移动端链接
                            hot_value=int(item.get('detail_text', '0').replace('万', '0000').replace('w', '0000') if item.get('detail_text') else 0),
                            description=target.get('excerpt', ''),
                            timestamp=int(datetime.now().timestamp()),
                            platform="zhihu"
                        ))
                    
                    return HotResponse(
                        platform="zhihu",
                        platform_name="知乎",
                        type="热榜",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items[:50]
                    )
            
        except Exception as e:
            logger.error(f"获取知乎数据失败: {str(e)}")
            return None
    
    async def _fetch_bilibili(self) -> Optional[HotResponse]:
        """获取B站排行榜"""
        try:
            url = "https://api.bilibili.com/x/web-interface/ranking/v2"
            params = {"rid": 0, "type": "all"}
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://www.bilibili.com'
            }
            
            async with self.session.get(url, params=params, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    for idx, video in enumerate(data.get('data', {}).get('list', [])):
                        url = f"https://www.bilibili.com/video/{video.get('bvid', '')}"
                        items.append(HotItem(
                            id=str(video.get('aid', idx)),
                            title=video.get('title', ''),
                            url=url,
                            mobile_url=url,  # 使用相同的URL作为移动端链接
                            hot=str(video.get('score', '')),
                            summary=video.get('desc', ''),
                            author=video.get('owner', {}).get('name', ''),
                            created_at=datetime.fromtimestamp(video.get('pubdate', 0)),
                            platform="bilibili"
                        ))
                    
                    return HotResponse(
                        platform="bilibili",
                        platform_name="哔哩哔哩",
                        type="排行榜",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items[:50]
                    )
            
        except Exception as e:
            logger.error(f"获取B站数据失败: {str(e)}")
            return None
    
    async def _fetch_weibo(self) -> Optional[HotResponse]:
        """获取微博热搜"""
        try:
            url = "https://weibo.com/ajax/side/hotSearch"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://weibo.com',
                'Cookie': settings.WEIBO_COOKIE or ''
            }
            
            async with self.session.get(url, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    for idx, item in enumerate(data.get('data', {}).get('realtime', [])):
                        url = f"https://s.weibo.com/weibo?q={item.get('word', '')}"
                        items.append(HotItem(
                            id=str(idx),
                            title=item.get('note', ''),
                            url=url,
                            mobile_url=url,  # 使用相同的URL作为移动端链接
                            hot=item.get('num', ''),
                            summary=item.get('word', ''),
                            created_at=datetime.now(),
                            platform="weibo"
                        ))
                    
                    return HotResponse(
                        platform="weibo",
                        platform_name="微博",
                        type="热搜",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items[:50]
                    )
            
        except Exception as e:
            logger.error(f"获取微博数据失败: {str(e)}")
            return None
    
    async def _fetch_github(self) -> Optional[HotResponse]:
        """获取GitHub趋势"""
        try:
            url = "https://api.github.com/search/repositories"
            params = {
                "q": "stars:>1000",
                "sort": "stars",
                "order": "desc",
                "per_page": 50
            }
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': 'application/vnd.github.v3+json',
                'Authorization': f'token {settings.GITHUB_TOKEN}' if settings.GITHUB_TOKEN else ''
            }
            
            async with self.session.get(url, params=params, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    for repo in data.get('items', [])[:50]:
                        url = repo.get('html_url', '')
                        items.append(HotItem(
                            id=str(repo.get('id', '')),
                            title=repo.get('full_name', ''),
                            url=url,
                            mobile_url=url,  # 使用相同的URL作为移动端链接
                            hot=str(repo.get('stargazers_count', 0)),
                            summary=repo.get('description', ''),
                            author=repo.get('owner', {}).get('login', ''),
                            created_at=datetime.fromisoformat(repo.get('created_at', '').replace('Z', '+00:00')),
                            platform="github"
                        ))
                    
                    return HotResponse(
                        platform="github",
                        platform_name="GitHub",
                        type="趋势",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items
                    )
            
        except Exception as e:
            logger.error(f"获取GitHub数据失败: {str(e)}")
            return None
    
    async def _fetch_36kr(self) -> Optional[HotResponse]:
        """获取36氪热榜"""
        try:
            url = "https://36kr.com/api/search-column/mainsite"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://36kr.com'
            }
            
            async with self.session.get(url, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    # 这里需要根据实际数据结构解析
                    # 暂时返回空数据
                    return HotResponse(
                        platform="36kr",
                        platform_name="36氪",
                        type="热榜",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items
                    )
            
        except Exception as e:
            logger.error(f"获取36氪数据失败: {str(e)}")
            return None
    
    async def _fetch_v2ex(self) -> Optional[HotResponse]:
        """获取V2EX热榜"""
        try:
            url = "https://www.v2ex.com/api/topics/hot.json"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            async with self.session.get(url, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    items = []
                    
                    for topic in data:
                        url = f"https://www.v2ex.com/t/{topic.get('id', '')}"
                        items.append(HotItem(
                            id=str(topic.get('id', '')),
                            title=topic.get('title', ''),
                            url=url,
                            mobile_url=url,  # 使用相同的URL作为移动端链接
                            hot=str(topic.get('replies', 0)),
                            summary=topic.get('content', ''),
                            author=topic.get('member', {}).get('username', ''),
                            created_at=datetime.fromtimestamp(topic.get('created', 0)),
                            platform="v2ex"
                        ))
                    
                    return HotResponse(
                        platform="v2ex",
                        platform_name="V2EX",
                        type="热榜",
                        total=len(items),
                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        data=items[:50]
                    )
            
        except Exception as e:
            logger.error(f"获取V2EX数据失败: {str(e)}")
            return None
    
    async def _fetch_generic(self, platform: str, config: Dict[str, Any]) -> Optional[HotResponse]:
        """通用数据获取方法"""
        try:
            url = config.get("api_url")
            method = config.get("method", "GET")
            headers = config.get("headers", {})
            params = config.get("params", {})
            
            async with self.session.request(method, url, headers=headers, params=params) as response:
                if response.status == 200:
                    data = await response.json()
                    
                    # 这里需要根据具体平台解析数据
                    # 暂时返回空数据
                    items = []
                    return HotResponse(
                        platform=platform,
                        platform_name=config.get("name", platform),
                        items=items,
                        updated_at=datetime.now()
                    )
            
        except Exception as e:
            logger.error(f"获取 {platform} 数据失败: {str(e)}")
            return None
    
    async def fetch_all_platforms(self) -> Dict[str, Optional[HotResponse]]:
        """获取所有平台数据"""
        platforms = platform_config.get_available_platforms()
        results = {}
        
        # 并发获取所有平台数据
        tasks = []
        for platform in platforms.keys():
            task = self.fetch_platform_data(platform)
            tasks.append((platform, task))
        
        for platform, task in tasks:
            result = await task
            results[platform] = result
        
        return results
    
    async def get_platforms_info(self) -> Dict[str, Dict[str, str]]:
        """获取平台信息"""
        platforms = platform_config.get_available_platforms()
        return {
            platform: {
                "name": config["name"],
                "type": config["type"],
                "description": config["description"]
            }
            for platform, config in platforms.items()
        }


# 创建服务实例
hot_data_service = HotDataService()